//
//  XTUserAccountViewModel.swift
//  HrenryWeibo
//
//  Created by 熊涛 on 16/5/13.
//  Copyright © 2016年 熊涛. All rights reserved.
//

import UIKit

class XTUserAccountViewModel: NSObject {

    //MARK: - 保存路径
    //归档解档路径
    let filePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! + "/account.plist"
    

    //账号,全局 只要拿到单例就可以拿到
    var userAccount : XTUserAccount?
    
    //判断是否登录--设置全局属性
    var isLogin : Bool {
        get {
//            XTPrint(items: "userAccount : \(userAccount)")
            return userAccount != nil
        }
    }
    
    //创建单例
    static let sharedInstance : XTUserAccountViewModel = XTUserAccountViewModel()
    
    
    override init() {
        super.init()
        //加载沙盒里面的账号,赋值给userAccount,只需要加载一次
        userAccount = loadUserAccount()
    }
    
    
    //发送POST请求,拿到AccessToken
    func loadAccessToken (code : String,callBack : (error : NSError?) -> ()) {
    
        let URLStr = "oauth2/access_token"
        let parameters = [
            "client_id" : client_id,
            "client_secret" : client_secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : redirect_uri
        ]
        XTNetWorkTool.sharedInstance.request(RequestMthod.POST, URLString: URLStr, parameters: parameters, progress: nil, success: { (task : NSURLSessionDataTask, response : AnyObject?) -> Void in
//            XTPrint(items: "response : \(response)")
            /*
            "access_token" = "2.00COdAXDwQ4gdE5c239eacf2e3uJoC";
            "expires_in" = 157679999;
            "remind_in" = 157679999;
            uid = 3236168370;
            */
            print("获得accessToken成功")
            if let dict = response as? [String : AnyObject] {
                //传入字典,获得模型数据
                let result =  XTUserAccount(dict: dict)
//                XTPrint(items: "result : \(result)")

//                XTPrint(items: "filePath : \(self.filePath)")
                //调用归档方法,将模型归档到沙盒当中
                NSKeyedArchiver.archiveRootObject(result, toFile: self.filePath)
//
                
                self.userAccount = result
                XTPrint(items: "self.userAccount : \(self.userAccount)")
                //完成后回调
                callBack(error: nil)
            }else {
                XTPrint(items: "转字典失败")
            }
            }, failure: { (task : NSURLSessionDataTask?, error : NSError) -> Void in
                XTPrint(items: "失败了error :\(error)")
                callBack(error: error)
        })
    }
    
    
    
    //发送GET请求,拿到用户的名称 跟 用户的头像
    func loadUserMessage(callBack : ((error : NSError?) -> ())) {
    
        //获取url
        let urlStr = "2/users/show.json"
        //参数
//        XTPrint(items: "userAccount?.access_token : \(userAccount)")
        let access_token = (userAccount?.access_token)! as String
        let uid = (userAccount?.uid)! as String
        let parameter = [
            "access_token" : access_token,
            "uid" : uid
        ]
        //发送请求
        XTNetWorkTool.sharedInstance.request(RequestMthod.GET, URLString: urlStr, parameters: parameter, progress: nil, success: { (task :NSURLSessionDataTask,responseObject : AnyObject?) -> Void in
            
            if let result = responseObject as? [String : AnyObject] {
                //
//               let userAccount = XTUserAccount(dict: result)
                self.userAccount?.screen_name = result["screen_name"] as? String
                self.userAccount?.avatar_large = result["avatar_large"] as? String
                
                //再次进行归档
                NSKeyedArchiver.archiveRootObject(self.userAccount!, toFile: self.filePath)
//                self.userAccount = userAccount
//                XTPrint(items: "self.userAccount : \(self.userAccount)")
                //回调
                callBack(error : nil)
            }else {
                XTPrint(items: "字典转模型失败")
            }
            
            
            }) { (task : NSURLSessionDataTask?, error :NSError) -> Void in
                XTPrint(items: "用户接口返回错误: \(error)")
                callBack( error: error)
        }
    }
    
    
    
    //解档
    private func loadUserAccount() -> XTUserAccount? {
    
//        XTPrint(items: "filePath : \(self.filePath)")
        if let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? XTUserAccount {
            
            //加载到账号,查看是否过期
            //userAccount.expiresDate 跟 当前的时间NSDate比较 
            //如果userAccount.expiresDate > NSDate 没有过期
            /*
            case OrderedAscending  升序
            case OrderedSame       相等
            case OrderedDescending 降序
            */
//             XTPrint(items: userAccount.access_token)
            if userAccount.expiresDate?.compare(NSDate()) != NSComparisonResult.OrderedAscending {
                
                XTPrint(items: "没有过期")
                return userAccount
            }else {
                XTPrint(items: "账号已经过期")
                return nil
            }
            
           
        }else {

            XTPrint(items: "没有存储账号")
            return nil
        }
        
    }
    
    
    
}
